package com.hmall.provider.Impl;

import com.hmall.provider.ChannelProvider;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class ZkChannelProvider implements ChannelProvider {

    private final Map<String, Channel> channelMap;

    public ZkChannelProvider() {
        channelMap = new ConcurrentHashMap<>();
    }

    @Override
    public Channel getChannel(InetSocketAddress inetSocketAddress) {
        String key = inetSocketAddress.toString();
        if (channelMap.containsKey(key)) {
            Channel channel = channelMap.get(key);
            if (channel != null && channel.isActive()) {
                return channel;
            }else {
                channelMap.remove(key);
            }
        }
        return null;
    }

    @Override
    public void setChannel(InetSocketAddress inetSocketAddress, Channel channel) {
        channelMap.put(inetSocketAddress.toString(), channel);
    }

    @Override
    public void removeChannel(InetSocketAddress inetSocketAddress) {
        channelMap.remove(inetSocketAddress.toString());
        log.info("Channel map size :[{}]", channelMap.size());
    }
}
